from socket import *
from select import *
import os


class WebServer:
    def __init__(self, HOST=None, PORT=None):
        self.HOST = HOST
        self.PORt = PORT
        self.ADDR = (HOST, PORT)
        self.rlist = []
        self.sock = self.connect()

    def connect(self):
        sock = socket()
        sock.bind(self.ADDR)
        return sock

    def connect_client(self):
        connfd, addr = self.sock.accept()
        print('Connect from', addr)
        connfd.setblocking(False)
        self.rlist.append(connfd)

    def show_web(self, connfd, info):
        if info == '/':
            file_name = './static/' + 'index.html'
        else:
            file_name = './static/' + info
        response = 'HTTP/1.1 200 ok\n'
        response += 'Content-Type: text/html\n'
        response += '\n'
        if os.path.exists(file_name):
            file = open(file_name, 'rb')
            data = file.read()
            connfd.send(response.encode() + data)
        else:
            data = '404!Sorry!'.encode()
            connfd.send(response.encode() + data)

    def handle(self, connfd):
        request = connfd.recv(1024).decode()
        if not request:
            return
        info = request.split(' ')[1]
        self.show_web(connfd, info)

    def start(self):
        self.sock.listen(5)
        self.rlist.append(self.sock)
        while True:
            rs, ws, xs = select(self.rlist, [], [])
            for r in rs:
                if r is self.sock:
                    self.connect_client()
                else:
                    self.handle(r)
                    self.rlist.remove(r)
                    r.close()


if __name__ == '__main__':
    web = WebServer('0.0.0.0', 8883)
    web.start()
